from sqlalchemy import Column, String, Text, Boolean, Integer, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.models.database import Base

# 笔记-文档关联表（多对多）
note_documents = Table(
    'note_documents',
    Base.metadata,
    Column('id', String(36), primary_key=True),
    Column('note_id', String(36), ForeignKey('notes.id', ondelete='CASCADE'), nullable=False),
    Column('document_id', String(36), ForeignKey('documents.id', ondelete='CASCADE'), nullable=False),
    Column('created_at', DateTime(timezone=True), server_default=func.now())
)


class Note(Base):
    """笔记模型"""
    __tablename__ = "notes"

    id = Column(String(36), primary_key=True, index=True)
    title = Column(String(255), nullable=False, index=True)
    content = Column(Text, nullable=False)
    
    # 所有者
    owner_id = Column(String(36), ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
    owner_name = Column(String(100))
    
    # 知识库关联（可选，加入知识库后才有）
    knowledge_base_id = Column(String(36), ForeignKey('knowledge_bases.id', ondelete='SET NULL'), nullable=True)
    
    # 向量化状态
    is_vectorized = Column(Boolean, default=False)
    vector_store_id = Column(String(100))  # 向量库中的ID
    
    # 公开状态（加入知识库后为 True）
    is_public = Column(Boolean, default=False)
    
    # 元数据（JSON格式存储：AI生成标记、来源类型等）
    extra_metadata = Column(Text)
    
    # 统计
    word_count = Column(Integer, default=0)
    
    # 时间
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    documents = relationship("Document", secondary=note_documents, backref="linked_notes")
    versions = relationship("NoteVersion", back_populates="note", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Note(title='{self.title}', owner='{self.owner_name}')>"


class NoteVersion(Base):
    """笔记版本历史"""
    __tablename__ = "note_versions"

    id = Column(String(36), primary_key=True, index=True)
    note_id = Column(String(36), ForeignKey('notes.id', ondelete='CASCADE'), nullable=False)
    
    # 快照内容
    title = Column(String(255), nullable=False)
    content = Column(Text, nullable=False)
    
    # 版本信息
    version_number = Column(Integer, nullable=False)
    created_by = Column(String(36), ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关联关系
    note = relationship("Note", back_populates="versions")
    
    def __repr__(self):
        return f"<NoteVersion(note_id='{self.note_id}', version={self.version_number})>"

